<template>
  <div>
    <NavBar :title="title"></NavBar>
    <view class="safe-box">
      <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
      <u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <u-form-item label="标题" prop="title" borderBottom ref="item1">
          <u--input v-model="formData.title" border="none" placeholder="请输入标题"></u--input>
        </u-form-item>
        <u-form-item label="价格" prop="price" borderBottom ref="item1">
          <u--input type='number' v-model="formData.price" border="none" placeholder="请输入价格(元)"></u--input>
        </u-form-item>
        <u-form-item label="发布时长" prop="duration" borderBottom ref="item1">
          <u--input type='number' v-model="formData.duration" border="none" placeholder="请输入发布时长"></u--input>
        </u-form-item>
        <u-form-item label="分类" prop="categoryId" borderBottom @click="showCategory = true;" ref="item1">
          <u--input v-model="categoryName" disabled disabledColor="#ffffff" placeholder="请选择分类" border="none"></u--input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>
        <!-- <u-form-item label="联系QQ" prop="qq" borderBottom ref="item1">
          <u--input type='number' v-model="formData.qq" border="none" placeholder="请输入发布时长"></u--input>
        </u-form-item> -->
        <u-form-item label="详情" prop="description" borderBottom ref="item1">
          <!-- <u--textarea v-model="formData.description" placeholder="请输入内容" autoHeight ></u--textarea> -->
          <u--input v-model="formData.description" border="none" placeholder="请输入详情信息"></u--input>
        </u-form-item>
        <u-form-item label="上传图片" prop="pictures" borderBottom ref="item1">
          <Upload v-model="formData.pictures" @afterRead="afterRead" @delete="deletePic" multiple>
          </Upload>
        </u-form-item>
      </u--form>
      <u-button type="primary" @click="submit">提交</u-button>
      <!-- <u-action-sheet :show="showSex" :actions="categories" title="分类" description="请选择分类"
              @close="showSex = false" @select="categorySelect">
          </u-action-sheet> -->
      <u-picker :show="showCategory" :columns="columns" keyName="name" @cancel="showCategory = false"
        @change="categorySelect" @confirm="categoryConfirm"></u-picker>
    </view>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 编辑当前是否为编辑商品
        id: null,
        title: '上传商品',
        columns: [
          [],
          []
        ],
        showCategory: false,
        formData: {
          user: '',
          categoryId: '',
          title: '',
          duration: '',
          price: '',
          description: '',
          pictures: [],
          qq: ''
        },
        categoryName: '',
        categories: [],
        rules: {
          categoryId: {
            type: 'string',
            required: true,
            message: '请选择分类',
            trigger: ['blur', 'change'],
          },
          title: {
            type: 'string',
            required: true,
            message: '请输入标题',
            trigger: ['blur', 'change'],
          },
          price: {
            type: 'number',
            required: true,
            message: '请输入价格',
            trigger: ['blur', 'change'],
          },
          duration: [{
              type: 'number',
              required: true,
              message: '请输入发布时长',
              trigger: ['blur', 'change'],
            },
            {
              // 自定义验证函数，见上说明
              validator: (rule, value, callback) => {
                console.log(value)
                if (value >= 1 && value <= 30) {
                  return true
                } else {
                  return false
                }
              },
              message: '只能在1-30天范围内',
              // 触发器可以同时用blur和change
              trigger: ['change', 'blur'],
            }
          ],
          description: {
            type: 'string',
            required: true,
            message: '请输入详情信息',
            trigger: ['blur', 'change'],
          },
          pictures: {
            type: 'array',
            required: true,
            message: '请上传主图',
            trigger: ['blur', 'change'],
          }
        },
      };
    },
    methods: {
      categorySelect(e) {
        console.log(e)
        const {
          columnIndex,
          index: current
        } = e
        if (columnIndex < this.columns.length - 1) {
          this.columns.splice(1, 1, this.categories[current].children)
        }
        // this.formData.categoryId = e._id
        // this.categoryName = e.name
      },
      categoryConfirm(e) {
        console.log(e)
        const lastValue = e.value[e.value.length - 1]
        this.formData.categoryId = lastValue._id
        this.categoryName = lastValue.name
        this.showCategory = false
      },
      getCategory() {
        console.log('----------------------')
        this.$http.get('/category').then(res => {
          console.log(res)
          this.categories = res.data
          res.data.forEach((item, i) => {
            this.columns[0].push(item)
          })
          this.columns[1] = res.data[0].children
        })
      },
      afterRead(e) {
        console.log('读取后的处理函数', e)
        this.$http.uploadFile(e.file.url).then(res => {
          console.log(res)
          this.formData.pictures.push(res.data)
        })
      },
      deletePic(e) {
        console.log('读取前的处理函数', e)
        this[`fileList${event.name}`].splice(e.index, 1)
      },
      submit() {
        console.log(this.formData)
        this.$refs.form.validate().then(res => {
          
          console.log(res)
          return res
        }).then((data) => {
          console.log(data)
          const {
            categoryId,
            title,
            price,
            description,
            pictures,
            duration,
            qq,
            state
          } = this.formData
          if (this.id) {
            this.$http.put('/goods', {
              id: this.id,
              category: categoryId,
              title,
              price,
              description,
              pictures,
              duration,
              qq,
              state
            }).then(() => {
              uni.$u.toast('修改成功')
              this.$nav.redirectTo('/pages/my-goods/my-goods')
            })
          } else {
            this.$http.post('/goods', {
              category: categoryId,
              title,
              price,
              description,
              pictures,
              duration,
              qq
            }).then(() => {
              uni.$u.toast('添加成功')
              this.$nav.redirectTo('/pages/my-goods/my-goods')
            })
          }
        })
      }
    },
    onLoad(e) {
      this.getCategory()
      console.log(e)
      if (e.id) {
        this.id = e.id
        this.$http.get(`/goods/${e.id}`).then(res => {
          console.log(res)
          this.formData = res.data
          this.categoryName = res.data.category.name
          this.formData.categoryId = res.data.category._id
        })
        this.title = '编辑商品'
      }
    }
  };
</script>
